import COS from 'cos-js-sdk-v5';
import api from "/@/api/common";

// COS 配置常量
const COS_CONFIG = {
  BUCKET: 'yj-mail-1307961934',
  REGION: 'ap-shanghai'
};

// 获取 COS 客户端实例
const getCos = (credentials: any) => {
  return new COS({
    async getAuthorization(options, callback) {
      callback({
        TmpSecretId: credentials.tmpSecretId,
        TmpSecretKey: credentials.tmpSecretKey,
        SecurityToken: credentials.sessionToken,
        StartTime: credentials.startTime,
        ExpiredTime: credentials.expiredTime,
      });
    },
  });
};

// 生成唯一文件名
const generateUniqueFileName = (fileName: string) => {
  const index = fileName.lastIndexOf('.');
  return `${fileName.substring(0, index)}_${new Date().getTime()}${fileName.substring(index)}`;
};

// 上传单个文件
const uploadSingleFile = (file: any, credentials: any) => {
  return new Promise((resolve, reject) => {
    const cos = getCos(credentials);
    const newName = generateUniqueFileName(file.name);
    
    cos.uploadFile({
      Bucket: COS_CONFIG.BUCKET,
      Region: COS_CONFIG.REGION,
      Key: newName,
      Body: file,
      SliceSize: 1024 * 1024 * 5,
    }, (err, data) => {
      if (err) {
        reject(err);
      } else {
        resolve({
          originalName: file.name,
          uploadedName: newName,
          url: `http://${data.Location}`
        });
      }
    });
  });
};

// 自定义多文件上传函数
export const customUploadMultiple = async (files: any[]) => {
  try {
    // 获取临时凭证
    const { data: credentials } = await api.getCredential();
    if (!credentials) {
      throw new Error('Failed to get COS credentials');
    }

    // 并发上传所有文件
    const uploadPromises = [...files].map(file => uploadSingleFile(file, credentials));
    const results = await Promise.all(uploadPromises);

    return results;
  } catch (error) {
    console.error('Upload failed:', error);
    return Promise.reject(error);
  }
};